package com.carp.springframework.beans.factory.support;

import cn.hutool.core.bean.BeanUtil;
import com.carp.springframework.beans.PropertyValue;
import com.carp.springframework.beans.PropertyValues;
import com.carp.springframework.beans.factory.config.BeanDefinition;
import com.carp.springframework.beans.factory.config.BeanReference;

import java.lang.reflect.Constructor;
import java.util.Objects;

/**
 * @author lile
 * @date 2023/2/2
 */
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory {

    protected InstantiationStrategy instantiationStrategy;

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) {
        Object bean = createBeanInstance(beanName, beanDefinition, args);
        applyPropertyValues(bean, beanDefinition);
        addSingleton(beanName, bean);
        return bean;
    }

    private Object createBeanInstance(String beanName, BeanDefinition beanDefinition, Object[] args) {
        Constructor<?> constructorToUse = null;
        Class<?> clazz = beanDefinition.getBeanClass();
        Constructor<?>[] declaredConstructors = clazz.getDeclaredConstructors();
        for (Constructor<?> ctor : declaredConstructors) {
            if (Objects.nonNull(args)) {
                Class<?>[] parameterTypes = ctor.getParameterTypes();
                if (parameterTypes.length == args.length) {
                    boolean flag = true;
                    for (int i = 0; i < parameterTypes.length; i++) {
                        if (!args[i].getClass().equals(parameterTypes[i])) {
                            flag = false;
                            break;
                        }
                    }
                    if (flag) {
                        constructorToUse = ctor;
                        break;
                    }
                }
            }
        }
        return instantiationStrategy.instantiate(beanDefinition, beanName, constructorToUse, args);
    }

    private void applyPropertyValues(Object bean, BeanDefinition beanDefinition) {
        PropertyValues propertyValues = beanDefinition.getPropertyValues();

        for (PropertyValue propertyValue : propertyValues.getPropertyValueList()) {
            String name = propertyValue.getName();
            Object value = propertyValue.getValue();
            if (value instanceof BeanReference) {
                BeanReference beanReference = (BeanReference) value;
                value = getBean(beanReference.getBeanName());
            }
            BeanUtil.setFieldValue(bean, name, value);
        }
    }

}
